#include <iostream>
#include <memory>
#include <vector>
#include "udpserver.hpp"

std::string handler(const std::string& str, const std::string& clientip, uint16_t clientport)
{
    std::cout << "[" << clientip << ":" << clientport << "]#";
    std::string ret = "Server get a message  #  " + str;

    return ret;
}

bool CmdCheck(const std::string& cmd)
{
    std::vector<std::string> key_word = 
    {
        "rm",
        "mv",
        "cp"
        "kill",
        "yum",
    }; 

    for(auto ch : key_word)
    {
        if(cmd.find(ch) != std::string::npos)
            return false;
    }

    return true;
}

std::string ExcuteCommand(const std::string& cmd, const std::string& clientip, uint16_t clientport)
{
    std::cout << "[" << clientip << ":" << clientport << "]# ";
    if(CmdCheck(cmd) == 0)
    {
        return "Bad command";
    }

    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        return 0;
    }
    char buffer[4096];
    std::string ret;
    while(1)
    {
        char* p = fgets(buffer, sizeof(buffer), fp);
        if(p == nullptr)
            break;

        ret += buffer;
    }

    return ret;
}

void usage(std::string proc)
{
    std::cout << "\n\rUsage : " << proc << "port[1023+]\n" << std::endl; 
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->init();

    svr->run(handler);

    return 0;
}